<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\StoreSetmeal as Model;
use app\admin\model\StoreMenu;
use app\admin\model\Store;

/**
 * 套餐管理管理
 */
class StoreSetmeal extends AdminBase
{
    /**
     * 套餐列表 - 分页
     * @param string $limit
     * @throws \think\db\exception\DbException
     */
    public function index($limit='10')
    {
        $model = new Model();
        $param = $this->request->param();
        if(!empty($param['name'])){
            $model = $model->where('name','like','%'.$param['name'].'%');
        }
        $lists = $model->order('id desc')->paginate($limit);
        $this->result(compact('lists'));
    }

    /**
     * 新增/编辑套餐
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $model = new Model();
            if(!empty($param['id'])){
                unset($param['create_time']);
                $model = Model::find($param['id']);
            }
            $result = $model->save($param);
            $this->result('',0,"操作成功");
        }
    }

    /**
     * 删除套餐
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否有用户
            $data = Store::where('setmeal_id',$param['id'])->find();
            if(!empty($data)){
                $this->result('',1,"该套餐底下有门店存在!不能删除");
            }else{
                Model::destroy($param['id']);
                $this->result('',0,"删除成功");
            }
        }
    }

    /**
     * 权限菜单列表
     */
    public function menu_list($role_id='')
    {
        if(empty($role_id)){
            $this->result('',1,"参数错误");
        }
        //读取所有菜单
        $list = StoreMenu::where('status',1)->select();
        //读取当前权限的菜单
        $role = Model::where('id',$role_id)->find();
        foreach ($list as $k=>$r){
            //如果存在
            $list[$k]['checked'] = in_array($r['id'],$role['roles']);
        }
        $this->result($list);
    }

    /**
     * 保存权限菜单
     * @return mixed
     */
    public function edit_roles()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Model::update($param,['id'=>$param['id']]);
            // 同步更新权限
            Model::sync_roles($param['id'],$param['roles']);
            $this->result('',0,"操作成功");
        }
    }

    /**
     * 读取套餐列表
     * @throws \think\db\exception\DbException
     */
    public function get_list()
    {
        $model = new Model();
        $lists = $model->order('id desc')->select();
        $this->result($lists);
    }
}
